'''
[移除链表元素](https://leetcode.cn/problems/remove-linked-list-elements/)
知识点：Optional 表示这个参数可以是 ListNode 类型，也可以是 None，即链表可能为空。
'''
from typing import Optional
class ListNode:
    def __init__(self, val=0, next=None):
            self.val = val
            self.next = next    

class Solution:
    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
        # 创建虚拟头部节点以简化删除过程
        dummy_head = ListNode(next = head)
        
        # 遍历列表并删除值为val的节点
        current = dummy_head
        while current.next:
            if current.next.val == val:
                current.next = current.next.next
            else:
                current = current.next
        
        return dummy_head.next

# 测试代码
if __name__ == "__main__":
    # 创建链表 1 -> 2 -> 6 -> 3 -> 4 -> 5 -> 6
    values = [1, 2, 6, 3, 4, 5, 6]  # 链表的值
    head = None
    for val in reversed(values):  # 从后往前构造链表
        head = ListNode(val, head)

    solution = Solution()
    # 移除值为6的节点
    new_head = solution.removeElements(head, 6)

    # 遍历并打印修改后的链表
    current = new_head
    while current:
        print(current.val, end=" -> ")
        current = current.next
    print("None")
